package com.atguigu.lease.web.app.service.impl;


import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.common.utils.VerifyCodeUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.SmsService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private SmsService smsService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserInfoService userInfoService;


    @Override
    public void getSmsCode(String phone) {
        // 1、检查手机号码是否为空
        if (!StringUtils.hasText(phone)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }

        // 生成验证码
        String code = VerifyCodeUtil.getVerifyCode(6);
        // 发送验证码
        smsService.sandCode(phone,code);

        // app登录 验证码的key
        String codeKey = RedisConstant.APP_LOGIN_PREFIX + phone;

        // 判断redis中是否有指定的codeKey
        Boolean result = stringRedisTemplate.hasKey(codeKey);

        // 如果成立，表示该手机号发送过短信了
        if (result) {
            // 获取验证码的有效期还剩多长时间
            Long expireTime = stringRedisTemplate.getExpire(codeKey);
            // 获取验证码的过期总时长
            Integer totalTime = RedisConstant.APP_LOGIN_CODE_TTL_SEC;
            // 判断是否在1分钟 内容发送的，如果是：向前端返回错误提示
            if (totalTime - expireTime < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC) {// 1分钟
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }
        // redis保存验证码
        // StringRedisTemplate的opsForValue()方法提供了对Redis中字符串类型数据的操作接口。
        // 设置向Redis添加键key 为codeKey ，值value 为code，验证码过期时间 1分钟，单位 秒
//        stringRedisTemplate.opsForValue().set(codeKey,code,RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);
            stringRedisTemplate.opsForValue().set(codeKey,code);
    }

    @Override
    public String login(LoginVo loginVo) {
        // 1、判断手机号码和验证码是否为空
        if(!StringUtils.hasText(loginVo.getPhone())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        if (!StringUtils.hasText(loginVo.getCode())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }

        // 2、校验验证码 是否过期 如果没有过期判断是否正确
        String key = RedisConstant.APP_LOGIN_PREFIX + loginVo.getPhone();
        String code = stringRedisTemplate.opsForValue().get(key);
        if (code == null) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }
        if (!code.equals(loginVo.getCode())) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }

        // 3、判断用户是否存在，不存在则创建新用户，并将用户保存至数据库中
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getPhone, loginVo.getPhone());
        UserInfo userInfo = userInfoService.getOne(queryWrapper);// 根据手机号获取用户的信息

        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setStatus(BaseStatus.ENABLE); // 用户状态正常
            userInfo.setNickname("我得发" + loginVo.getPhone().substring(5));
            userInfoService.save(userInfo);
        }

        // 4、判断用户是否被禁
        if (userInfo.getStatus() == BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }

        // 创建token 并且返回
        String appToken = JwtUtil.createToken(userInfo.getId(), loginVo.getPhone());
        System.out.println(userInfo);


        return appToken;
    }

    @Override
    public UserInfoVo getUserInfoById(Long userId) {
        UserInfo userInfo = userInfoService.getById(userId);
        UserInfoVo userInfoVo = new UserInfoVo(userInfo.getNickname(), userInfo.getAvatarUrl());
        return userInfoVo;
    }
}
